import axios, { type AxiosRequestConfig } from 'axios'

export const request = axios.create({
  timeout: 5000,
})

// 1. 声明缓存请求的集合
const pendingRequests = new Map()
// 2. 基于请求的url和method生成key
function generateRequestKey<T extends AxiosRequestConfig>(config: T) {
  const { method, url } = config
  return [method, url].join('&')
}
// 3. 缓存正在pending状态的请求
function addPendingRequest(config: AxiosRequestConfig) {
  const requestKey = generateRequestKey(config)
  if (!pendingRequests.has(requestKey)) {
    // 如果是新的请求，创建AbortController并绑定到请求
    const controller = new AbortController()
    config.signal = controller.signal
    pendingRequests.set(requestKey, controller)
  }
  else {
    // 如果请求已经存在，取消之前的请求并删除记录
    const controller = pendingRequests.get(requestKey)
    controller?.abort()
    pendingRequests.delete(requestKey)
  }
}
// 4.响应完删除集合
function removePendingRequest(config: AxiosRequestConfig) {
  const requestKey = generateRequestKey(config)
  if (pendingRequests.has(requestKey)) {
    pendingRequests.delete(requestKey)
  }
}

request.interceptors.request.use(
  (config) => {
    addPendingRequest(config)
    config.headers.Authorization = 'Bearer Z6t9FgrJbMFFLfDfxuPf8GjlSxdKmrxWWMYC7vzWfB8ArBY6dwDimtjmSqsxFHq0iIQ21ujMjjQuiprPnouam0MKehDmBlGqH58hZgFnV6IS3QUqKEEahqoDHYTyDH8T'
    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

request.interceptors.response.use(
  (response) => {
    removePendingRequest(response.config)
    return response
  },
  (error) => {
    return Promise.reject(error)
  },
)
